<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <form class="login-form" @submit.prevent="handlelogin">
        <div class="avatar-container">
          <div class="avatar">
            <svg xmlns="http://www.w3.org/2000/svg" width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
          </div>
        </div>
        
        <h2 class="title">投产演练平台</h2>
        <p class="sub mb">输入您的账号和密码</p>
        
        <input
          type="text"
          class="input"
          placeholder="用户ID"
          v-model="authId"
          required
          autocomplete="username"
        />
        

        
        <input
          type="password"
          class="input"
          placeholder="密码"
          v-model="password"
          required
          autocomplete="current-password"
        />
        
        <!-- 登录错误提示 -->
        <div v-if="loginError" class="alert error">{{ loginError }}</div>
        
        <button type="submit" class="submit-button" :disabled="loading">
          <span v-if="loading">登录中...</span>
          <span v-else>登录</span>
        </button>
        
        <div class="login-options">
          <label class="remember-me">
            <input type="checkbox" v-model="rememberMe" class="checkbox">
            记住我
          </label>
          <a href="#" class="forgot-password" @click.prevent="handleForgotPassword">忘记密码?</a>
        </div>
        
        <p class="sub">
          还没有账号? <a href="#" @click.prevent="handleRegister">立即注册</a>
        </p>
      </form>
    </div>
  </div>
  
  <!-- 注册模态框 -->
  <div v-if="showRegisterModal" class="modal-overlay" @click="closeRegisterModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">用户注册</h3>
        <button class="modal-close" @click="closeRegisterModal">×</button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="submitRegisterForm">
          <!-- 注册成功提示 -->
          <div v-if="registerSuccess" class="alert success">{{ registerSuccess }}</div>
          <!-- 注册错误提示 -->
          <div v-if="registerError" class="alert error">{{ registerError }}</div>
          
          <input
            type="text"
            class="input"
            placeholder="用户ID"
            v-model="registerUsername"
            required
            autocomplete="username"
          />
          
          <input
            type="email"
            class="input"
            placeholder="邮箱"
            v-model="registerEmail"
            required
            autocomplete="email"
          />
          
          <input
            type="password"
            class="input"
            placeholder="密码"
            v-model="registerPassword"
            required
            autocomplete="new-password"
          />
          
          <input
            type="password"
            class="input"
            placeholder="确认密码"
            v-model="confirmPassword"
            required
            autocomplete="new-password"
          />
          
          <button type="submit" class="submit-button">注册</button>
        </form>
      </div>
    </div>
  </div>
  
  <!-- 忘记密码模态框 -->
  <div v-if="showForgotPasswordModal" class="modal-overlay" @click="closeForgotPasswordModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">忘记密码</h3>
        <button class="modal-close" @click="closeForgotPasswordModal">×</button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="submitForgotPassword">
          <!-- 成功提示 -->
          <div v-if="forgotPasswordSuccess" class="alert success">{{ forgotPasswordSuccess }}</div>
          <!-- 错误提示 -->
          <div v-if="forgotPasswordError" class="alert error">{{ forgotPasswordError }}</div>
          
          <p class="sub mb">请输入您注册时使用的邮箱地址，我们将向您发送重置密码的链接</p>
          
          <input
            type="email"
            class="input"
            placeholder="邮箱"
            v-model="forgotPasswordEmail"
            required
            autocomplete="email"
          />
          
          <button type="submit" class="submit-button">发送重置链接</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import authService from '../services/authService';
import userService from '../services/userService';

const router = useRouter();
// 登录表单数据
const authId = ref('');

const password = ref('');
const rememberMe = ref(false);

// 注册表单数据
const showRegisterModal = ref(false);
const registerUsername = ref('');
const registerEmail = ref('');
const registerPassword = ref('');
const confirmPassword = ref('');
const registerError = ref('');
const registerSuccess = ref('');

// 忘记密码表单数据
const showForgotPasswordModal = ref(false);
const forgotPasswordEmail = ref('');
const forgotPasswordError = ref('');
const forgotPasswordSuccess = ref('');

// 添加登录状态和错误提示
const loading = ref(false);
const loginError = ref('');

// 处理登录逻辑
const handlelogin = async () => {
  // 重置错误提示
  loginError.value = '';
  
  // 验证表单
  if (!authId.value || !password.value) {
    loginError.value = '请输入账号和密码';
    return;
  }
  
  // 设置加载状态
  loading.value = true;
  
  try {
    // 调用登录API
    const response = await authService.login({
      authId: authId.value,
      password: password.value
    });
    
    // 登录成功，保存用户信息
    localStorage.setItem('user', JSON.stringify(response.data));
    
    // 如果勾选了记住我，保存到localStorage
    if (rememberMe.value) {
      localStorage.setItem('rememberedAuthId', authId.value);
    } else {
      localStorage.removeItem('rememberedAuthId');
    }
    
    // 跳转到数据源配置页面
    router.push('/data-source-configuration');
  } catch (error) {
    // 处理登录错误
    console.error('登录失败:', error);
    loginError.value = error.response?.data?.message || '登录失败，请检查账号密码后重试';
  } finally {
    // 关闭加载状态
    loading.value = false;
  }
};

// 显示注册模态框
const handleRegister = () => {
  showRegisterModal.value = true;
  registerError.value = '';
  registerSuccess.value = '';
};

// 关闭注册模态框
const closeRegisterModal = () => {
  showRegisterModal.value = false;
  // 重置表单
  registerUsername.value = '';
  registerEmail.value = '';
  registerPassword.value = '';
  confirmPassword.value = '';
  registerError.value = '';
  registerSuccess.value = '';
};

// 显示忘记密码模态框
const handleForgotPassword = () => {
  showForgotPasswordModal.value = true;
  forgotPasswordError.value = '';
  forgotPasswordSuccess.value = '';
};

// 关闭忘记密码模态框
const closeForgotPasswordModal = () => {
  showForgotPasswordModal.value = false;
  // 重置表单
  forgotPasswordEmail.value = '';
  forgotPasswordError.value = '';
  forgotPasswordSuccess.value = '';
};

// 提交忘记密码请求
const submitForgotPassword = async () => {
  forgotPasswordError.value = '';
  forgotPasswordSuccess.value = '';
  
  // 验证邮箱格式
  const emailRegex = /^[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+(?:\.[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+)*@(?:[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+\.)+[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+$/;
  if (!forgotPasswordEmail.value || !emailRegex.test(forgotPasswordEmail.value)) {
    forgotPasswordError.value = '请输入有效的邮箱地址';
    return;
  }
  
  try {
    // 调用后端API发送重置密码邮件
    await userService.forgotPassword(forgotPasswordEmail.value);
    
    // 处理成功响应
    forgotPasswordSuccess.value = '重置密码邮件已发送，请查收您的邮箱';
    
    // 清空邮箱输入
    forgotPasswordEmail.value = '';
    
    // 5秒后自动关闭模态框
    setTimeout(() => {
      closeForgotPasswordModal();
    }, 5000);
    
  } catch (error) {
    // 处理错误响应
    console.error('发送重置密码邮件失败:', error);
    forgotPasswordError.value = error.response?.data?.message || '发送邮件失败，请稍后重试';
  }
};

// 表单验证函数
const validateRegisterForm = () => {
  if (!registerUsername.value || !registerEmail.value || !registerPassword.value) {
    registerError.value = '请填写所有必填字段';
    return false;
  }
  
  // 验证邮箱格式
  const emailRegex = /^[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+(?:\.[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+)*@(?:[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+\.)+[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+$/;
  if (!emailRegex.test(registerEmail.value)) {
    registerError.value = '请输入有效的邮箱地址';
    return false;
  }
  
  // 验证密码长度
  if (registerPassword.value.length < 6) {
    registerError.value = '密码长度至少为6位';
    return false;
  }
  
  // 验证两次输入的密码是否一致
  if (registerPassword.value !== confirmPassword.value) {
    registerError.value = '两次输入的密码不一致';
    return false;
  }
  
  return true;
};

// 提交注册表单
const submitRegisterForm = async () => {
  registerError.value = '';
  registerSuccess.value = '';
  
  // 表单验证
  if (!validateRegisterForm()) {
    return;
  }
  
  try {
    // 构建注册数据对象
    const userData = {
      username: registerUsername.value,
      email: registerEmail.value,
      password: registerPassword.value,
      role: '普通用户' // 默认角色
    };
    
    // 调用后端API创建用户
    const response = await userService.createUser(userData);
    
    // 处理注册成功
    registerSuccess.value = '注册成功！请使用您的账号登录';
    
    // 重置表单
    registerUsername.value = '';
    registerEmail.value = '';
    registerPassword.value = '';
    confirmPassword.value = '';
    
    // 3秒后自动关闭模态框
    setTimeout(() => {
      closeRegisterModal();
    }, 3000);
    
  } catch (error) {
    // 处理注册失败
    console.error('注册失败:', error);
    registerError.value = error.response?.data?.message || '注册失败，请稍后重试';
  }
};

// 模拟检查用户是否已登录的逻辑
const checkloginStatus = () => {
  const user = localStorage.getItem('user');
  if (user) {
    router.push('/data-source-configuration');
  }
};

// 组件挂载时检查登录状态
checkloginStatus();
</script>

<style scoped>
/* 登录页面容器样式 */
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background: var(--bg-main);
  /* 应用网站主题的背景渐变 */
  background: radial-gradient(125% 125% at 50% 10%, #fff 40%, #63e 100%);
  /* 确保容器占满整个屏幕 */
  width: 100vw;
  margin: 0;
  box-sizing: border-box;
}

/* 登录表单包装器 */
.login-form-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 20px;
}

/* 登录表单样式 - 优化居中效果和视觉体验 */
.login-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
  width: 100%;
  max-width: 400px;
  background-color: var(--bg-white);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  /* 确保表单本身是居中的 */
  margin: 0 auto;
}

.login-form:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg), 0 15px 30px rgba(99, 102, 241, 0.15);
}

/* 标题样式 */
.title {
  color: var(--text-primary);
  font-weight: bold;
  text-align: center;
  font-size: var(--font-size-xl);
  margin: var(--spacing-md) 0 var(--spacing-xs);
}

/* 副标题样式 */
.sub {
  text-align: center;
  color: var(--text-regular);
  font-size: var(--font-size-sm);
  width: 100%;
  margin: 0;
}

.sub.mb {
  margin-bottom: var(--spacing-md);
}

.sub a {
  color: var(--primary-color);
  text-decoration: none;
  transition: color 0.2s ease;
}

.sub a:hover {
  color: var(--primary-hover);
  text-decoration: underline;
}

/* 头像样式 */
.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: var(--spacing-md);
}

.avatar {
  height: 60px;
  width: 60px;
  background-color: var(--primary-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: var(--shadow-md);
  transition: all 0.3s ease;
}

.avatar:hover {
  background-color: var(--primary-hover);
  transform: scale(1.05);
  box-shadow: var(--shadow-lg);
}

/* 输入框和按钮样式 */
.input {
  border: 1px solid var(--border-base);
  outline: none;
  width: 100%;
  padding: var(--spacing-md) var(--spacing-sm);
  background-color: var(--bg-light);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  color: var(--text-primary);
  transition: all 0.3s ease;
}

.input:focus {
  border: 1px solid var(--primary-color);
  background-color: var(--bg-white);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.input::placeholder {
  color: var(--text-placeholder);
}

.submit-button {
  margin-top: var(--spacing-md);
  background-color: var(--primary-color);
  color: white;
  border: none;
  outline: none;
  width: 100%;
  padding: var(--spacing-md) var(--spacing-sm);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
}

.submit-button:hover {
  background-color: var(--primary-hover);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.submit-button:active {
  background-color: var(--primary-active);
  transform: translateY(0);
  box-shadow: var(--shadow-sm);
}

/* 登录选项样式 */
.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: var(--spacing-xs);
}

.remember-me {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--text-regular);
  cursor: pointer;
}

.checkbox {
  accent-color: var(--primary-color);
}

.forgot-password {
  font-size: var(--font-size-sm);
  color: var(--primary-color);
  text-decoration: none;
  transition: color 0.2s ease;
}

.forgot-password:hover {
  color: var(--primary-hover);
  text-decoration: underline;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-form-wrapper {
    padding: var(--spacing-md);
  }
  
  .login-form {
    padding: var(--spacing-lg);
    max-width: 100%;
  }
  
  .title {
    font-size: var(--font-size-lg);
  }
}

/* 注册模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-lg);
  padding: 0;
  width: 100%;
  max-width: 400px;
  box-shadow: var(--shadow-lg);
  animation: slideUp 0.3s ease;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-light);
}

.modal-title {
  margin: 0;
  color: var(--text-primary);
  font-size: var(--font-size-lg);
  font-weight: bold;
}

.modal-close {
  background: none;
  border: none;
  font-size: var(--font-size-xl);
  color: var(--text-placeholder);
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--border-radius-base);
  transition: all 0.2s ease;
}

.modal-close:hover {
  background-color: var(--bg-light);
  color: var(--text-primary);
}

.modal-body {
  padding: var(--spacing-lg);
}

/* 提示信息样式 */
.alert {
  padding: var(--spacing-md);
  border-radius: var(--border-radius-base);
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-sm);
}

.alert.success {
  background-color: rgba(34, 197, 94, 0.1);
  color: var(--success-color);
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.alert.error {
  background-color: rgba(239, 68, 68, 0.1);
  color: var(--error-color);
  border: 1px solid rgba(239, 68, 68, 0.3);
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>